package com.seasugar.raggie.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自定义 Entity 处理器
 */
@Component
@Slf4j
public class MyMetaObjectHandle implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]");
        if(metaObject.hasSetter("createUser"))
        metaObject.setValue("createUser",BaseContext.getCurrentId());
        if(metaObject.hasSetter("updateUser"))
        metaObject.setValue("updateUser",BaseContext.getCurrentId());

        if(metaObject.hasSetter("createTime"))
        metaObject.setValue("createTime", LocalDateTime.now());
        if(metaObject.hasSetter("updateTime"))
        metaObject.setValue("updateTime", LocalDateTime.now());
        log.info(metaObject.toString());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]");
        Long id = Thread.currentThread().getId();
        log.info("线程id为:{}",id);
//        ThreadLocal<Long> threadLocal=new ThreadLocal<>();
//        log.info(String.valueOf(BaseContext.getCurrentId()));
        if(metaObject.hasSetter("updateUser"))
        metaObject.setValue("updateUser",BaseContext.getCurrentId());
        log.info("当前更新用户id为：{}",BaseContext.getCurrentId());
        if(metaObject.hasSetter("updateTime"))
        metaObject.setValue("updateTime", LocalDateTime.now());
        log.info(metaObject.toString());
    }
}
